package com.bdqn;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class PersonReflection_7 {
    public static void main(String[] args) {
        try{
            Class clz = Class.forName("com.bdqn.Person");
            //获取无参构造函数
            Constructor c1 = clz.getDeclaredConstructor();
            //无参构造函数为public 这里可以直接访问
            Object obj = c1.newInstance();
            System.out.println(obj);

            //获取private 的 单构参数造函数
            Constructor c2 = clz.getDeclaredConstructor(String.class);
            //构造函数为private 超出访问不能直接访问
            //通过setAccessable方法设定为可以访问
            c2.setAccessible(true);
            obj = c2.newInstance("New Person");
            System.out.println(obj);

            //获取三参构造 protected
            Constructor c3 = clz.getDeclaredConstructor(String.class,String.class,String.class);
            //超出访问范围
            c3.setAccessible(true);
            obj = c3.newInstance("New Person","beijing","Hello!");
            System.out.println(obj);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
